package com.linkhub.oms.admin.modules.stock.compute;

import com.linkhub.oms.common.util.QtOptionalUtil;
import com.linkhub.oms.common.util.QtStreamUtil;
import com.linkhub.oms.entity.ProductStockEntity;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @Description: StockCreator
 * @Author: echo
 * @Date: 2024/4/28 14:35
 * @Version: 1.0
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StockCreator implements Serializable {


    private List<ProductStockEntity> productStocks;

    @Getter
    private Map<String, Integer> availableStockMap;

    public static StockCreator create(List<ProductStockEntity> productStocks) {
        return new StockCreator(productStocks).availableStock();
    }

    private StockCreator(List<ProductStockEntity> productStocks) {
        this.productStocks = productStocks;
    }

    private List<ProductStockEntity> getProductStocks() {
        return productStocks;
    }

    private StockCreator availableStock() {
        availableStockMap = QtStreamUtil.toMap(this.getProductStocks(),
                ProductStockEntity::getSkuId,
                ProductStockEntity::computeAvailableStock);
        return this;
    }

    public Integer getSkuAvailableStock(String skuId) {
        return QtOptionalUtil.of(this.getAvailableStockMap())
                .map(map -> map.getOrDefault(skuId, 0))
                .orElse(0);
    }
}
